package com.box.common.utils;

import net.sf.json.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.util.*;

/**
 * @author dengguangming
 */
public class ApiUtil {
    //IC卡号
    static String iccid = "8986111922903515005";

    static String appId = "zx20201022153530";
    static String appkey = "95241145e9bfdd556bbfd50ac681efff";
    static String v = "2.0";
    static String domain = "http://admin.rysms.cn";

    public static void main(String[] args) {
        //查询单个号码当前生命周期状态
        //queryRequst("queryCardStatus");

        //查询单个号码的信息
        queryRequst("queryCardInfo");

        //提供单个号码的月流量包订购//验签失败
        //orderCardPackage();

        //单个号码的套餐查询
        //queryRequst("queryCardPackage");

        //提供单个号码的流量信息实时查询
        //queryRequst("queryCardTraffic");

        //提供单个故障号码转移到新卡//null
        //queryRequst("exChangeCard");

        //查询卡片实名进度情况
        //queryRequst("getCardRealNameStatus");

        queryRequst("sign");
    }

    static private void queryRequst(String apiMethod) {
        String url = domain + ":8898/iot/api/" + apiMethod;
        Map<String, String> map = getCommonParam();
        if ("sign".equals(apiMethod)) {
            map.put("appKey", appkey);
        }
        map.put("sign", sign(map, appkey));
        JSONObject json = JSONObject.fromObject(map);
        System.out.println(doPosts(url, json));
    }

    static private void orderCardPackage() {
        String url = domain + ":8898/iot/api/orderCardPackage";
        Map<String, String> map = getCommonParam();
        map.put("packageId", "1788");
        map.put("orderAmount", "29.9");
        map.put("sign", sign(map, appkey));
        JSONObject json = JSONObject.fromObject(map);
        System.out.println(doPosts(url, json));
    }

    static private Map getCommonParam() {
        Map<String, String> map = new HashMap();
        map.put("iccid", iccid);
        map.put("appId", appId);
        map.put("v", v);
        map.put("timestamp", System.currentTimeMillis() + "");
        return map;
    }

    /**
     * 使用secret对paramValues按以下算法进行签名：
     */
    public static String sign(Map<String, String> paramValues, String secret) {
        return sign(paramValues, null, secret);
    }

    /**
     * 签名算法，其中ignoreParamNames这些参数不参与签名
     */
    public static String sign(Map<String, String> paramValues, List<String> ignoreParamNames, String secret) {
        try {
            byte[] sha1Digest = getSHA1Digest(getSignStr(paramValues, ignoreParamNames, secret));
            return byte2hex(sha1Digest);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String getSignStr(Map<String, String> paramValues, List<String> ignoreParamNames, String secret) {
        StringBuilder sb = new StringBuilder();
        List<String> paramNames = new ArrayList<>(paramValues.size());
        paramNames.addAll(paramValues.keySet());
        if (ignoreParamNames != null && ignoreParamNames.size() > 0) {
            for (String ignoreParamName : ignoreParamNames) {
                paramNames.remove(ignoreParamName);
            }
        }
        Collections.sort(paramNames);
        sb.append(secret);
        for (String paramName : paramNames) {
            sb.append(paramName).append(paramValues.get(paramName));
        }
        sb.append(secret);
        return sb.toString();
    }

    private static byte[] getSHA1Digest(String data) throws IOException {
        byte[] bytes = null;
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-1");
            bytes = md.digest(data.getBytes("UTF-8"));
        } catch (GeneralSecurityException gse) {
            throw new IOException(gse);
        }
        return bytes;
    }

    /**
     * 二进制转十六进制字符串
     */
    private static String byte2hex(byte[] bytes) {
        StringBuilder sign = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(bytes[i] & 0xFF);
            if (hex.length() == 1) {
                sign.append("0");
            }
            sign.append(hex.toUpperCase());
        }
        return sign.toString();
    }

    public static JSONObject doPosts(String url, JSONObject json) {
        CloseableHttpClient httpclient = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(url);
        JSONObject response = null;
        try {
            StringEntity s = new StringEntity(json.toString());
            s.setContentEncoding("UTF-8");
            s.setContentType("application/json");//发送json数据需要设置contentType
            post.setEntity(s);
            HttpResponse res = httpclient.execute(post);
            if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                String result = EntityUtils.toString(res.getEntity());// 返回json格式：
                response = JSONObject.fromObject(result);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        //System.out.println(response);
        return response;
    }

}
